package cn.kgc.thread.demo2;

import java.util.concurrent.*;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

/**
 * @description:
 * @author: 石浩杰
 * @date: 2022-12-14 08:35
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        /*(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new ScheduledThreadPoolExecutor.DelayedWorkQueue());(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new ScheduledThreadPoolExecutor.DelayedWorkQueue());*/
        ScheduledExecutorService scheduledExecutorService=Executors.newScheduledThreadPool(10);
        scheduledExecutorService.schedule(() -> System.out.println("线程池中执行的操作"),5,TimeUnit.SECONDS);
    }

    private static void extracted3() {
        /*new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());*/
        //可缓存线程池
        ExecutorService executorService=Executors.newCachedThreadPool();
        executorService.execute(()->{
            System.out.println("线程要执行的任务");
        });
    }

    private static void extracted2() {
        /*new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());*/
        ExecutorService executorService=Executors.newFixedThreadPool(10);
        executorService.execute(()->{
            System.out.println("线程要执行的任务");
        });
    }

    private static void extracted1() {
        /*new Executors.FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>()));*/
        //创建一个单实例的线程
        ExecutorService executorService=Executors.newSingleThreadExecutor();

        executorService.execute(()->{
            System.out.println("线程要执行的任务");
        });
    }

    private static void extracted() {
        //corePoolSize:核心线程数
        //maximumPoolSize:最大线程数
        //keepAliveTime:空闲线程存活时间(超过核心线程数的线程，空闲的时间)
        //workQueue:线程的队列 直接交接队列 有界队列 无界队列
        //threadFactory:线程工厂
        //拒绝策略
        ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(5,10,5, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
        threadPoolExecutor.execute(()->{
            System.out.println("线程池中执行的任务"+Thread.currentThread().getName());
        });

        //关闭线程池:shutdown关闭线程，线程池中的任务继续执行，但是此时就不能向线程池中添加任务
        threadPoolExecutor.shutdown();
    }
}
